package summary;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/12 15:57
 * https://leetcode-cn.com/problems/house-robber-iii/
 */
public class Title337 {

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(){}

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    static Map<TreeNode, Integer> hashMap;

    /**
     * 关键是要讨论当前节点抢还是不抢
     * @param root
     * @return
     */
    public int rob(TreeNode root) {
        hashMap = new HashMap<>();
        return backTracking(root);
    }

    private int backTracking(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return root.val;
        }
        if (hashMap.get(root) != null) {
            return hashMap.get(root);
        }
        //偷父节点
        int val = root.val;
        if (root.left != null) {
            val += rob(root.left.left) + rob(root.left.right);
        }
        if (root.right != null) {
            val += rob(root.right.left) + rob(root.right.right);
        }
        //不偷父节点
        int val2 = rob(root.left) + rob(root.right);
        int maxValue = Math.max(val, val2);
        hashMap.put(root, maxValue);
        return maxValue;
    }


    /**
     * dp[0]表示该节点不偷 dp[1]表示该节点偷
     * @param root
     * @return
     */
    public int rob1(TreeNode root) {
        int[] result = traversal(root);
        return Math.max(result[0], result[1]);
    }

    private int[] traversal(TreeNode root) {
        int[] dp = new int[2];
        if (root == null) {
            return dp;
        }
        int[] left = traversal(root.left);
        int[] right = traversal(root.right);
        dp[0] = Math.max(left[0], left[1]) + Math.max(right[0], right[1]);
        dp[1] = root.val + left[0] + right[0];
        return dp;
    }


    public static void main(String[] args) {

    }
}
